package com.vegetable.modules.controller.wx;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vegetable.common.annotation.SysLog;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.finance.PaymentPurchase;
import com.vegetable.modules.entity.wx.WXApproval;
import com.vegetable.modules.mapper.finance.PaymentPurchaseMapper;
import com.vegetable.modules.service.finance.UnionPayService;
import com.vegetable.modules.service.finance.impl.WxApprovalPayeeInfoExtractor;
import com.vegetable.modules.service.wx.WXApprovalService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.oa.WxCpApprovalDetailResult;
import me.chanjar.weixin.cp.bean.oa.WxCpSpStatus;
import me.chanjar.weixin.cp.bean.oa.applydata.ApplyDataContent;
import me.chanjar.weixin.cp.bean.oa.applydata.ContentValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Map;

/**
 * 企业微信审批回调控制器
 * 处理企业微信异步回调通知
 *
 * @author Qoder
 */
@Slf4j
@RestController
@RequestMapping("/wx/approval/callback")
public class WxApprovalCallbackController extends AbstractController {

    @Autowired
    private WxCpService wxCpService;

    @Autowired
    private WXApprovalService wxApprovalService;

    @Autowired
    private PaymentPurchaseMapper paymentPurchaseMapper;

    @Autowired
    private UnionPayService unionPayService;

    /**
     * 企业微信审批回调接口
     * 当审批状态发生变化时，企业微信会主动调用此接口通知系统
     */
    @PostMapping("/notify")
    public R handleApprovalCallback(@RequestBody String callbackData) {
        try {
            log.info("收到企业微信审批回调通知: {}", callbackData);
            
            // 解析回调数据
            JSONObject callbackJson = JSON.parseObject(callbackData);
            
            // 获取审批编号
            String spNo = callbackJson.getString("sp_no");
            if (spNo == null || spNo.isEmpty()) {
                log.warn("回调数据中缺少审批编号");
                return R.fail("回调数据格式错误");
            }
            
            // 获取审批详情
            WxCpApprovalDetailResult detailResult = wxCpService.getOaService().getApprovalDetail(spNo);
            if (detailResult == null || detailResult.getErrCode() != 0) {
                log.error("获取审批详情失败，审批编号: {}, 错误码: {}", spNo, 
                    detailResult != null ? detailResult.getErrCode() : "null");
                return R.fail("获取审批详情失败");
            }
            
            // 处理审批结果
            return processApprovalResult(detailResult);
        } catch (WxErrorException e) {
            log.error("处理企业微信审批回调时发生微信异常", e);
            return R.fail("处理审批回调失败: " + e.getMessage());
        } catch (Exception e) {
            log.error("处理企业微信审批回调时发生异常", e);
            return R.fail("处理审批回调失败: " + e.getMessage());
        }
    }

    /**
     * 处理审批结果
     */
    private R processApprovalResult(WxCpApprovalDetailResult detailResult) {
        try {
            // 获取审批信息
            WxCpApprovalDetailResult.WxCpApprovalDetail approvalInfo = detailResult.getInfo();
            String spNo = approvalInfo.getSpNo();
            String spName = approvalInfo.getSpName();
            
            // 只处理付款审批
            if (!"付款审批".equals(spName)) {
                log.info("非付款审批，跳过处理，审批名称: {}", spName);
                return R.success("非付款审批，无需处理");
            }
            
            // 查找对应的审批记录
            WXApproval wxApproval = wxApprovalService.selectBySPNO(spNo);
            if (wxApproval == null) {
                // 创建新的审批记录
                wxApproval = createWXApprovalFromDetail(detailResult);
                wxApprovalService.save(wxApproval);
            } else {
                // 更新审批记录
                updateWXApprovalFromDetail(wxApproval, detailResult);
                wxApprovalService.updateById(wxApproval);
            }
            
            // 根据审批状态执行相应操作
            String spStatus = wxApproval.getSpStatus();
            switch (spStatus) {
                case "PASSED": // 已通过
                    return handleApproved(wxApproval, approvalInfo);
                case "REJECTED": // 已驳回
                    return handleRejected(wxApproval);
                case "UNDONE": // 已撤销
                    return handleRevoked(wxApproval);
                default:
                    log.info("审批状态未变更，审批编号: {}, 状态: {}", spNo, spStatus);
                    return R.success("审批状态未变更");
            }
        } catch (Exception e) {
            log.error("处理审批结果时发生异常", e);
            return R.fail("处理审批结果失败: " + e.getMessage());
        }
    }

    /**
     * 处理审批通过
     */
    private R handleApproved(WXApproval wxApproval, WxCpApprovalDetailResult.WxCpApprovalDetail approvalInfo) {
        try {
            Long paymentId = wxApproval.getPaymentId();
            if (paymentId == null) {
                log.warn("审批记录中缺少付款ID，审批ID: {}", wxApproval.getId());
                return R.fail("审批记录数据不完整");
            }
            
            // 获取付款记录
            PaymentPurchase payment = paymentPurchaseMapper.selectById(paymentId);
            if (payment == null) {
                log.warn("付款记录不存在，付款ID: {}", paymentId);
                return R.fail("付款记录不存在");
            }
            
            // 检查付款状态
            if (payment.getState() != 2) { // 2表示审批中
                log.info("付款状态不正确，当前状态: {}, 付款ID: {}", payment.getState(), paymentId);
                return R.success("付款状态不正确，无需处理");
            }
            
            // 从审批详情中获取收款人信息
            String payeeName = payment.getCustomerName();
            String payeeBankAccount = "";
            String payeeBankName = "";
            
            // 解析审批详情中的内容，获取收款人信息
            try {
                // 使用工具类提取收款人信息
                Map<String, String> payeeInfo = WxApprovalPayeeInfoExtractor.extractPayeeInfo(approvalInfo);
                payeeName = payeeInfo.get("payeeName");
                payeeBankAccount = payeeInfo.get("payeeBankAccount");
                payeeBankName = payeeInfo.get("payeeBankName");
            } catch (Exception e) {
                log.warn("解析审批详情中的收款人信息时发生异常", e);
            }
            
            // 执行支付，传递收款人信息
            R payResult = unionPayService.executeSinglePayment(
                payment, 
                payeeName, 
                payeeBankAccount, 
                payeeBankName
            );
            
            if (payResult.getCode() == 0) {
                // 支付成功
                payment.setState(1); // 1表示实际已付
                payment.setRemitTime(new Date()); // 设置打款时间
                paymentPurchaseMapper.updateById(payment);
                
                // 更新审批状态
                wxApproval.setSpStatus("ALREADY_PAY"); // ALREADY_PAY表示已支付
                wxApprovalService.updateById(wxApproval);
                
                // 同步状态到企业微信
                boolean syncResult = wxApprovalService.syncApprovalStatusToWechat(wxApproval.getSpNo(), "ALREADY_PAY");
                if (!syncResult) {
                    log.warn("同步审批状态到企业微信失败，审批编号: {}", wxApproval.getSpNo());
                }
                
                // 发送通知给申请人
                // notifyApplicant(payment, "付款已完成", true);
                
                log.info("支付成功，付款ID: {}", paymentId);
                return R.success("支付成功");
            } else {
                // 支付失败
                payment.setState(5); // 5表示支付失败
                paymentPurchaseMapper.updateById(payment);
                
                // 发送通知给申请人
                // notifyApplicant(payment, "支付失败: " + payResult.getMsg(), false);
                
                log.error("支付失败，付款ID: {}, 错误信息: {}", paymentId, payResult.getMsg());
                return R.fail("支付失败: " + payResult.getMsg());
            }
        } catch (Exception e) {
            log.error("处理审批通过时发生异常", e);
            return R.fail("处理审批通过失败: " + e.getMessage());
        }
    }

    /**
     * 处理审批驳回
     */
    private R handleRejected(WXApproval wxApproval) {
        try {
            Long paymentId = wxApproval.getPaymentId();
            if (paymentId == null) {
                log.warn("审批记录中缺少付款ID，审批ID: {}", wxApproval.getId());
                return R.fail("审批记录数据不完整");
            }
            
            // 获取付款记录
            PaymentPurchase payment = paymentPurchaseMapper.selectById(paymentId);
            if (payment == null) {
                log.warn("付款记录不存在，付款ID: {}", paymentId);
                return R.fail("付款记录不存在");
            }
            
            // 更新付款状态为审批拒绝
            payment.setState(4); // 4表示审批拒绝
            paymentPurchaseMapper.updateById(payment);
            
            // 发送通知给申请人
            // notifyApplicant(payment, "付款申请被驳回", false);
            
            log.info("付款审批被驳回，付款ID: {}", paymentId);
            return R.success("付款审批已驳回");
        } catch (Exception e) {
            log.error("处理审批驳回时发生异常", e);
            return R.fail("处理审批驳回失败: " + e.getMessage());
        }
    }

    /**
     * 处理审批撤销
     */
    private R handleRevoked(WXApproval wxApproval) {
        try {
            Long paymentId = wxApproval.getPaymentId();
            if (paymentId == null) {
                log.warn("审批记录中缺少付款ID，审批ID: {}", wxApproval.getId());
                return R.fail("审批记录数据不完整");
            }
            
            // 获取付款记录
            PaymentPurchase payment = paymentPurchaseMapper.selectById(paymentId);
            if (payment == null) {
                log.warn("付款记录不存在，付款ID: {}", paymentId);
                return R.fail("付款记录不存在");
            }
            
            // 更新付款状态为结账未付
            payment.setState(0); // 0表示结账未付
            paymentPurchaseMapper.updateById(payment);
            
            // 发送通知给申请人
            // notifyApplicant(payment, "付款申请已撤销", false);
            
            log.info("付款审批已撤销，付款ID: {}", paymentId);
            return R.success("付款审批已撤销");
        } catch (Exception e) {
            log.error("处理审批撤销时发生异常", e);
            return R.fail("处理审批撤销失败: " + e.getMessage());
        }
    }

    /**
     * 从审批详情创建WXApproval对象
     */
    private WXApproval createWXApprovalFromDetail(WxCpApprovalDetailResult detailResult) {
        WXApproval wxApproval = new WXApproval();
        
        WxCpApprovalDetailResult.WxCpApprovalDetail approvalInfo = detailResult.getInfo();
        
        wxApproval.setSpNo(approvalInfo.getSpNo());
        wxApproval.setSpName(approvalInfo.getSpName());
        wxApproval.setSpStatus(approvalInfo.getSpStatus().name());
        wxApproval.setUserId(approvalInfo.getApplier().getUserId());
        wxApproval.setApplyTime(new Date(approvalInfo.getApplyTime() * 1000));
        wxApproval.setSpComment(JSON.toJSONString(detailResult));
        
        // 解析审批金额（这里需要根据实际的审批表单结构来解析）
        // 暂时设置为0，实际应用中需要根据表单结构解析
        wxApproval.setMoney(BigDecimal.ZERO);
        
        return wxApproval;
    }

    /**
     * 从审批详情更新WXApproval对象
     */
    private void updateWXApprovalFromDetail(WXApproval wxApproval, WxCpApprovalDetailResult detailResult) {
        WxCpApprovalDetailResult.WxCpApprovalDetail approvalInfo = detailResult.getInfo();
        
        wxApproval.setSpStatus(approvalInfo.getSpStatus().name());
        wxApproval.setSpComment(JSON.toJSONString(detailResult));
        
        // 更新时间
        wxApproval.setUpdateTime(new Date());
    }
}